package io.renren.modules.generator.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.*;
import io.renren.common.vo.ImportResultVo;
import io.renren.common.vo.OrderAddressesVo;
import io.renren.common.vo.ProductAddressVo;
import io.renren.common.vo.TmsOrderVo;
import io.renren.modules.generator.dao.OrdersDao;
import io.renren.modules.generator.entity.*;
import io.renren.modules.generator.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, OrdersEntity> implements OrdersService {

    @Autowired
    private ProductService productService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private TransitTimeService transitTimeService;

    @Autowired
    private OrderDetailService detailService;


    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrdersGroupService ordersGroupService;


    @Autowired
    private RedisService redisService;

    private static   Pattern compile = Pattern.compile("^[0-9]+$");



    @Override
    public List<OrdersEntity> queryPage(Map<String, Object> params) {


        return ordersDao.queryPage(params);
    }

    @Override
    @Transactional
    public R importPdfData(MultipartFile[] multipartFiles) throws IOException {
        /**
         * 一、解析所有文件中的订单：
         *      1、保存有效的订单（校验每一个字段），要确保文件中的所有订单都有效，才保存：List<Map<fileName,List<OrdersEntity>>>
         *      2、保存无效的订单和文件名，只要文件中的一个订单无效，则整个文件无效；List<Map<fileName,orderNumber+错误信息>>
         * 二、遍历有效的文件订单集合，进行保存
         *      1、拿到订单的R0之前的号码，先校验此次此订单在系统中是否存在
         *          （1）如果不存在，直接保存，记录成功的文件名和订单号
         *          （2）、订单完全相同，不保存，直接跳过，记录相同文件名和订单号，
         *          （3）、订单是需要修改的： 比较R数字的大小，判断是否要更新，记录修改的文件名和订单号
         * 三、返回结果
         *
         */

        LocalDateTime localDateTime = LocalDateTime.now();
        String createdTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));



        String createdBy = ShiroUtils.getUserEntity().getUsername();

        /**
         * 记录有校的文件名和订单，
          */
        List<Map<String,List<OrdersEntity>>> validFileNameList = new ArrayList<>();


        /**
         *记录无效的文件名和错误信息
         */

        List<ImportResultVo> invalidFileNameList= new ArrayList<>();



        PDDocument document = null;

        for (int i = 0; i < multipartFiles.length; i++) {
            try{

                /**
                 * 记录有效的订单列表
                 */
                List<OrdersEntity> validOrdersEntityList = new ArrayList<>();



                /**
                 * 有效的文件名和订单map
                 */

                Map<String, List<OrdersEntity>> validFielNameOrdersEntityList = new HashMap<>();



                /**
                 * 错误信息map
                 */
                ImportResultVo resultVo = new ImportResultVo();


                /**
                 * 错误信息：订单号+错误信息
                 */
                 StringBuffer errorMsgSb = new StringBuffer("");

                MultipartFile file = multipartFiles[i];
                String filename = file.getOriginalFilename();

                document = PDDocument.load(file.getBytes());


                // 获取页码
                int endPage = document.getNumberOfPages();
                int startPage = 1;

                PDFTextStripper stripper = new PDFTextStripper();
                stripper.setSortByPosition(true);
                while (startPage <= endPage) {

                    stripper.setStartPage(startPage);
                    stripper.setEndPage(startPage);

                    String pdfFileInText = stripper.getText(document);
                    /**
                     * 整个pdf页面的字符串
                     */
                    String[] strings = pdfFileInText.split("\\r?\\n");


                    /**
                     * 订单号
                     */
                    String orderNumber = strings[5].split(":")[1].trim();
                    /**
                     * 不含 R1的订单号
                     */
                    String orderNo = orderNumber.split("\\s")[0];



                    int length = strings.length;


                    /**
                     * 有效的订单明细
                     */
                    List<OrderDetailEntity> validOrderDetailEntityList = new ArrayList<>();


                    /**
                     * 产品的客户id,一张单子上的产品肯定属于同一个客户
                     */

                    Integer customerId=null;

                    /**
                     * 取出货品信息
                     */
                    for (int j = 17; j < length; j++) {
                        if (strings[j].contains("合计(Total)")) {
                            break;
                        }
                        String[] split = strings[j].split("\\s+");
                        /**
                         * 产品编码
                         */
                        String productNumber = split[0];
                        if(!compile.matcher(productNumber).matches()){
                            continue;
                        }
                        /**
                         * 数量
                         */
                        String quantity = split[split.length - 1].replaceAll(",", "");


                        /**
                         * 判断产品信息是否存在
                         */

                        ProductEntity productEntity =null;
                        Object o = redisService.get(RedisKeys.getProductKey(productNumber));
                        if(o == null){
                            productEntity = productService.queryByNumber(productNumber);
                            if(productEntity != null){
                                redisService.set(RedisKeys.getProductKey(productNumber),productEntity,600L);
                            }

                        }else{
                          productEntity = (ProductEntity) o;
                        }


                        if (productEntity == null) {
                            errorMsgSb.append("<div style='margin-top: 5px;margin-left: 15px'>"+orderNumber+"  :产品"+productNumber+"没有维护，请维护;</div>");
                            continue;
                        }

                        customerId = productEntity.getCustomerId();
                        OrderDetailEntity orderDetailEntity = new OrderDetailEntity();

                        orderDetailEntity.setProductId(productEntity.getId());
                        Double aDouble = Double.valueOf(quantity);
                        if(productEntity.getDefaultMeasurementUnitNumber() != 0){
                            orderDetailEntity.setPlatesNumber(aDouble/productEntity.getDefaultMeasurementUnitNumber());
                        }
                        orderDetailEntity.setQuantity(Double.valueOf(quantity));
                        orderDetailEntity.setWeight(productEntity.getGrossWeight()*aDouble);
                        orderDetailEntity.setVolume(productEntity.getVolume()*aDouble);
                        orderDetailEntity.setProductNumber(productNumber);
                        validOrderDetailEntityList.add(orderDetailEntity);


                    }


                    if(errorMsgSb.length() > 0){
                        startPage++;
                        continue;
                    }

                    String[] fromAddressStr = strings[6].split("\\s+");

                    String toDtAreaCode = orderNumber.substring(0, 2).trim();




                    OrderDetailEntity orderDetailEntity = validOrderDetailEntityList.get(0);


                    /**
                     * 到货地址信息,通过订单前两位，查找地址名称，可能有多个：当有多个时，订单的提货和到货地址不维护，记录需要修改的订单
                     */
                    AddressEntity toAddress=null;
                    AddressEntity fromAddress=null;
                   // List<AddressEntity> addressList =null;
                  //  String toAddressKey = RedisKeys.getAddressKey(toDtAreaCode);
                  //  Object o = redisService.get(toAddressKey);
                   // if(o == null){
                    List<ProductAddressVo> addressList = addressService.queryToAddressByToAddressNameAndProductId(toDtAreaCode,orderDetailEntity.getProductId());

                        if(addressList == null || addressList.size() == 0){
                            errorMsgSb.append("<div style='margin-top: 5px;margin-left: 15px'>"+orderNumber+"  :  到货地址："+toDtAreaCode+"没有维护，请先维护或者在产品中激活;</div>");
                            startPage++;
                            continue;
                        }else if(addressList != null && addressList.size() == 1){
                            if(addressList.get(0) != null){
                                toAddress = addressList.get(0).getToAddress();
                                fromAddress = addressList.get(0).getFromAddress();
                            }



                           // redisService.set(toAddressKey,toAddress,Constant.getRedisKeyExpireTimeMinutesToSecond(10));

                        }

                   // }else{
                    //    toAddress = (AddressEntity) o;
                   // }





                    /**
                     * 由到货地和产品id查询提货地址
                     */
                    String fromDate =null;

                    String toDateStr = fromAddressStr[3];    //到货日期
                    if(toAddress != null){
                       // Set<AddressEntity> fromAddresses = addressService.queryFromAddressEntityListByToAddressIdAndProductId(toAddress.getId(), orderDetailEntity.getProductId());


                      /*  if(fromAddresses == null || fromAddresses.size() == 0){
                            errorMsgSb.append("<div style='margin-top: 5px;margin-left: 15px'>"+orderNumber+"  :  由产品"+orderDetailEntity.getProductNumber()+"的到货地址："+toDtAreaCode+"没有找到相应的提货地址，请先维护或激活;</div>");
                            startPage++;
                            continue;
                        }*/

                      /*  else if(fromAddresses.size() ==1){
                            Iterator<AddressEntity> iterator = fromAddresses.iterator();
                            fromAddress = iterator.next();
                        }*/

                        if(fromAddress != null){
                            /**
                             * 查询在途时间
                             */
                            List<Integer> fromDtAreaIds = new ArrayList<>();
                            List<Integer> toDtAreaIds = new ArrayList<>();

                            fromDtAreaIds.add(fromAddress.getDtAreaId());
                            toDtAreaIds.add(toAddress.getDtAreaId());
                            TransitTimeEntity transitTimeEntity = transitTimeService.queryTimeByFromDtAreaIdsAndToDtAreaIds(fromDtAreaIds, toDtAreaIds);

                            /**
                             * 计算提货日期
                             */



                            if(transitTimeEntity != null){
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
                                Date toDate = simpleDateFormat.parse(toDateStr);
                                Calendar rightNow = Calendar.getInstance();
                                rightNow.setTime(toDate);
                                rightNow.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + (transitTimeEntity.getTime()-1)));
                                Date time = rightNow.getTime();
                                fromDate = simpleDateFormat.format(time);
                            }
                        }

                    }




                    /**
                     * 有效的订单信息
                     */
                    OrdersEntity validOrdersEntity = new OrdersEntity();
                    /**
                     * 保存订单号
                     */
                    validOrdersEntity.setOrderNumber(orderNumber);
                    /**
                     * 保存R0之前的单号
                     */
                    validOrdersEntity.setOrderNo(orderNo);
                    /**
                     * 创建人
                     */
                    validOrdersEntity.setCreatedBy(createdBy);
                    /**
                     * 创建时间
                     */
                    validOrdersEntity.setCreatedTime(createdTime);
                    /**
                     * 新建状态
                     */
                    validOrdersEntity.setStatus(Constant.OrderStatus.NEW.getValue());
                    /**
                     * 保存订单明细
                     */
                    validOrdersEntity.setOrderDetails(validOrderDetailEntityList);

                    validOrdersEntity.setFromDate(fromDate);

                    validOrdersEntity.setToDate(toDateStr);

                    validOrdersEntity.setCustomerId(customerId);

                    validOrdersEntity.setFromAddress(fromAddress);
                    validOrdersEntity.setToAddress(toAddress);

                    validOrdersEntityList.add(validOrdersEntity);

                    startPage++;
                }
                if(errorMsgSb.length() > 0){

                    resultVo.setFileName(filename);
                    resultVo.setMsg(errorMsgSb);
                    invalidFileNameList.add(resultVo);

                    continue;
                }
                if(validOrdersEntityList != null && validOrdersEntityList.size() > 0){
                    validFielNameOrdersEntityList.put(filename,validOrdersEntityList);

                    validFileNameList.add(validFielNameOrdersEntityList);
                }

            }catch (Exception e){
                e.printStackTrace();
                return R.error();
            }finally {
                document.close();
            }
        }

        List<ImportResultVo> saveSuccessFileNameList = new ArrayList<>();
        List<ImportResultVo> updateSuccessFileNameList = new ArrayList<>();
        List<ImportResultVo> sameSuccessFileNameList = new ArrayList<>();
        /**
         * 记录到货地址和提货地不完整的订单
         */
        List<ImportResultVo> orderInfoIsNotCompleteList = new ArrayList<>();





        try{
            if(validFileNameList.size() > 0){
                for (Map<String, List<OrdersEntity>> map :
                        validFileNameList) {

                    Set<String> filNameSets = map.keySet();
                    for (String fileName: filNameSets) {

                        ImportResultVo saveSuccess = new ImportResultVo();
                        StringBuffer saveSuccessOrder = new StringBuffer("");

                        ImportResultVo updateSuccess = null;
                        StringBuffer updateSuccessOrder = null;
                        ImportResultVo sameSuccess = new ImportResultVo();
                        StringBuffer sameSuccessOrder = new StringBuffer("");


                        /**
                         * 记录到货地址和提货地不完整的订单map
                         */
                        ImportResultVo orderInfoIsNotCompleteVo = new ImportResultVo();

                        /**
                         * 记录到货地址和提货地不完整的订单列表
                         */
                        StringBuffer orderInfoIsNotCompleteSb = new StringBuffer("");


                        List<OrdersEntity> ordersEntities = map.get(fileName);

                        for (OrdersEntity newOrdersEntity :ordersEntities) {
                            String orderNo = newOrdersEntity.getOrderNo();
                            String orderKey = RedisKeys.getOrderKey(orderNo);
                          //  Object o = redisService.get(orderKey);
                            //OrdersEntity oldOrderEntity =null;
                          //  if(o ==null){
                            OrdersEntity oldOrderEntity = queryEntityByOrderNo(orderNo);

                           // }else{
                           //     oldOrderEntity = (OrdersEntity) o;
                          //  }




                            if(oldOrderEntity == null){

                                this.save(newOrdersEntity);
                              //  redisService.set(orderKey,newOrdersEntity,Constant.getRedisKeyExpireTimeMinutesToSecond(10));
                                saveSuccessOrder.append("<div style='margin-top: 5px;margin-left: 15px'>"+newOrdersEntity.getOrderNumber()+";</div>");
                                saveSuccess.setFileName(fileName);
                                saveSuccess.setMsg(saveSuccessOrder);

                                if(newOrdersEntity.getToAddress() == null || newOrdersEntity.getFromAddress() == null){
                                    orderInfoIsNotCompleteSb.append("<div style='margin-top: 5px;margin-left: 15px'>"+newOrdersEntity.getOrderNumber()+" ;</div>");
                                }


                            }else{
                                String newOrderNumber = newOrdersEntity.getOrderNumber();
                                String oldOrderNumber = oldOrderEntity.getOrderNumber();

                                int newNum =Integer.valueOf( newOrderNumber.substring(newOrderNumber.lastIndexOf("R") + 1,
                                        newOrderNumber.length())).intValue();

                                int oldNum = Integer.valueOf(oldOrderNumber.substring(oldOrderNumber.lastIndexOf("R")+1,
                                        oldOrderNumber.length())).intValue();

                                /**
                                 * 修改的单子
                                 */
                                if(newNum >oldNum ){
                                    updateSuccess = new ImportResultVo();
                                    updateSuccessOrder = new StringBuffer("");

                                    if(oldOrderEntity.getStatus().equals(Constant.OrderStatus.ALREADY_CREATED_GROUP.getValue()) ||
                                            oldOrderEntity.getStatus().equals(Constant.OrderStatus.ALREADY_CREATED_DISPATCH.getValue())){
                                        updateSuccessOrder.append("<div style='margin-top: 5px;margin-left: 15px'>订单号"+oldOrderNumber+Constant.OrderStatus.getName(oldOrderEntity.getStatus()) +"无法修改为"+newOrderNumber+";</div>");
                                        updateSuccess.setFileName(fileName);
                                        updateSuccess.setMsg(updateSuccessOrder);
                                    }else{
                                        this.deleteById(oldOrderEntity.getId());
                                        detailService.deleteByOrderId(oldOrderEntity.getId());
                                        this.save(newOrdersEntity);
                                        redisService.set(orderKey,newOrdersEntity,Constant.getRedisKeyExpireTimeMinutesToSecond(10));


                                        updateSuccessOrder.append("<div style='margin-top: 5px;margin-left: 15px'>订单号由"+oldOrderNumber+"改为"+newOrderNumber+";</div>");
                                        updateSuccess.setFileName(fileName);
                                        updateSuccess.setMsg(updateSuccessOrder);

                                        saveSuccessOrder.append("<div style='margin-top: 5px;margin-left: 15px'>"+newOrdersEntity.getOrderNumber()+"; </div>");
                                        saveSuccess.setFileName(fileName);
                                        saveSuccess.setMsg(saveSuccessOrder);

                                        if(newOrdersEntity.getToAddress() == null || newOrdersEntity.getFromAddress() == null){
                                            orderInfoIsNotCompleteSb.append("<div style='margin-top: 5px;margin-left: 15px'>"+newOrdersEntity.getOrderNumber()+" ;</div>");
                                        }
                                    }
                                    /**
                                     * 相同的单子
                                     */
                                }else if(newNum == oldNum){
                                    redisService.set(orderKey,oldOrderEntity,Constant.getRedisKeyExpireTimeMinutesToSecond(10));
                                    sameSuccessOrder.append("<div style='margin-top: 5px;margin-left: 15px'>"+newOrderNumber+";</div>");
                                    sameSuccess.setFileName(fileName);
                                    sameSuccess.setMsg(sameSuccessOrder);
                                }
                            }

                        }
                        if(saveSuccess != null && saveSuccess.getFileName() != null){
                            saveSuccessFileNameList.add(saveSuccess);
                        }
                        if(updateSuccess !=null && updateSuccess.getFileName() != null){
                            updateSuccessFileNameList.add(updateSuccess);
                        }
                        if(sameSuccess != null && sameSuccess.getFileName() != null){
                            sameSuccessFileNameList.add(sameSuccess);
                        }
                        if(orderInfoIsNotCompleteSb.length() >0 ){
                            orderInfoIsNotCompleteVo.setFileName(fileName);
                            orderInfoIsNotCompleteVo.setMsg(orderInfoIsNotCompleteSb);
                            orderInfoIsNotCompleteList.add(orderInfoIsNotCompleteVo);

                        }


                    }

                }
            }
            /**
             * 报异常时，reids的key也将无法保存，将会回滚
             */
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


        return R.ok().put("errorMsg",invalidFileNameList)
                .put("saveSuccessMsg",saveSuccessFileNameList)
                .put("updateSuccessMsg",updateSuccessFileNameList)
                .put("sameSuccessMsg",sameSuccessFileNameList)
                .put("infoIsNotCompleteMsg",orderInfoIsNotCompleteList);

    }



    @Override
    public int queryPageTotal(Map<String, Object> params) {
        return ordersDao.queryPageTotal(params);
    }

    @Override
    public void save(OrdersEntity orders) {
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        setOrderAddress(orders);
        orders.setCreatedBy(ShiroUtils.getUserEntity().getUsername());
        orders.setCreatedTime(format);
        String orderNo = orders.getOrderNumber().trim().split(" ")[0];
        orders.setOrderNo(orderNo);
        orders.setStatus(Constant.OrderStatus.NEW.getValue());
        this.insert(orders);
        saveOrderDetails(orders.getOrderDetails(),orders.getId());

    }


    private OrdersEntity queryEntityByOrderNo(String orderNo){
        return this.selectOne(new EntityWrapper<OrdersEntity>().eq(StringUtils.isNotBlank(orderNo),"order_no",orderNo));
    }


    @Override
    public void update(OrdersEntity orders) {
        setOrderAddress(orders);
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orders.setLastModifiedTime(format);
        orders.setOrderNo(orders.getOrderNumber().trim().split(" ")[0]);
        this.updateById(orders);
        OrderDetailEntity orderDetailEntity = orders.getOrderDetails().get(0);
        orderDetailEntity.setLastModifiedTime(format);
        orderDetailEntity.setLastModifiedBy(ShiroUtils.getUserEntity().getUsername());
        detailService.updateById(orderDetailEntity);
    }



    @Override
    public Map<String,Set<Map<String, String>>> queryAllFromAddressAndAllToAddress() {
        List<OrderAddressesVo> addressAndAllToAddress = ordersDao.queryAllFromAddressAndAllToAddress();


        Set<Map<String, String>> fromAddresses = addressAndAllToAddress.stream().filter(orderAddressesVo -> {
            if(orderAddressesVo != null && orderAddressesVo.getFromAddress() != null){
                return  true;
            }
            return false;
        }).map(OrderAddressesVo::getFromAddress).collect(Collectors.toSet());
        Set<Map<String, String>> toAddresses = addressAndAllToAddress.stream().filter(orderAddressesVo -> {
            if(orderAddressesVo != null && orderAddressesVo.getToAddress() != null){
                return  true;
            }
            return false;
        }).map(OrderAddressesVo::getToAddress).collect(Collectors.toSet());

        Map<String,Set<Map<String, String>>> map =new HashMap<>();

        map.put(Constant.AddressProperty.FROM_ADDRESS.getProperty() ,fromAddresses);
        map.put(Constant.AddressProperty.TO_ADDRESS.getProperty(),toAddresses);

        return map;
    }

    @Override
    public void updateOrderStatusByIds(String status, Collection<Integer> ids) {
        ordersDao.updateOrderStatusByIds(status,ids);
    }

    @Override
    @Transactional
    public void cancelOrderGroupByIds(Map<Integer, List<Integer>> map) {


        Set<Integer> integers = map.keySet();
        Set<String> toDtAreaIds=null;
        Set<String> toDtAreaNames=null;
        Set<String> fromDtAreaIds=null;
        Set<String> fromDtAreaNames=null;
        for (Integer id :
                integers) {
            List<OrdersEntity> ordersEntities = ordersDao.selectList(new EntityWrapper<OrdersEntity>()
                    .eq(id != null, "order_group_id", id));

            if(ordersEntities != null && ordersEntities.size() == map.get(id).size()){
                ordersGroupService.deleteById(id);
            }


            ordersDao.orderGroupOptionByIds(Constant.OrderStatus.CANCEL_GROUP.getValue(),map.get(id),null);

            List<Integer> orderIds = map.get(id);

            for ( OrdersEntity entity: ordersEntities) {
                if(!orderIds.contains(entity.getId().intValue())){
                    toDtAreaIds=new HashSet<>();
                    toDtAreaNames=new HashSet<>();
                    fromDtAreaIds=new HashSet<>();
                    fromDtAreaNames=new HashSet<>();

                    toDtAreaIds.add(entity.getToDtAreaId().toString());
                    toDtAreaNames.add(entity.getToCity());
                    fromDtAreaIds.add(entity.getFromDtAreaId().toString());
                    fromDtAreaNames.add(entity.getFromCity());
                }
            }

            String toIds = StringUtils.join(toDtAreaIds,",");
            String toNames = StringUtils.join(toDtAreaNames,"+");
            String fromIds = StringUtils.join(fromDtAreaIds,",");
            String fromNames = StringUtils.join(fromDtAreaNames,"+");


            if(toIds != null && !toIds.equals("") && fromIds != null && !fromIds.equals("")){
                ordersGroupService.updateDtAreaById(toIds,toNames,fromIds,fromNames,id);

            }

        }

    }

    @Override
    public void cancelOrderGroupByOrderGroupId(int orderGroupId) {
        ordersDao.cancelOrderGroupByOrderGroupId(orderGroupId);
    }

    @Override
    public void orderCreatedGroupByIds(Set<Integer> orderIds, Integer orderGroupId) {
        ordersDao.orderGroupOptionByIds(Constant.OrderStatus.ALREADY_CREATED_GROUP.getValue(),orderIds,orderGroupId);
    }


    @Override
    public void updateOrderStatusById(String status, Integer id) {
        ordersDao.updateOrderStatusById(status,id);
    }


    @Override
    public OrdersEntity queryByOrderDetailIdAndOrderId(String orderId, String orderDetailId) {
        return ordersDao.queryByOrderDetailIdAndOrderId(orderId,orderDetailId);
    }

    @Override
    public List<OrdersEntity> queryOrder(String status, String orderGroupNumber, Set<String> toAddressIds) {
        return ordersDao.queryOrder(status,orderGroupNumber,toAddressIds);
    }

    @Override
    public List<OrdersEntity> queryOrdersByOrderGroupId(int orderGroupId) {
        return ordersDao.queryOrdersByOrderGroupId(orderGroupId);
    }

    @Override
    public void addOrderToOrderGroup(Set<Integer> orderIds, int orderGroupId) {
        Set<Map<String,String>> dtArea = queryToDtAreaIdsByOrderIds(orderIds);
        OrdersGroupEntity ordersGroupEntity = ordersGroupService.selectById(orderGroupId);

        String toDtAreaIds = ordersGroupEntity.getToDtAreaIds();
        String toDtAreaNames = ordersGroupEntity.getToDtAreaNames();
        String fromDtAreaIds = ordersGroupEntity.getFromDtAreaIds();
        String fromDtAreaNames = ordersGroupEntity.getFromDtAreaNames();

        for (Map <String,String> map: dtArea
             ) {
            String toDtAreaId = map.get("toDtAreaId");
            if(toDtAreaIds.indexOf(toDtAreaId) < 0){
                String toCity = map.get("toCity");
                toDtAreaIds+=","+toDtAreaId;
                toDtAreaNames+="+"+toCity;

            }
            String fromDtAreaId = map.get("fromDtAreaId");
            if(fromDtAreaIds.indexOf(fromDtAreaId) < 0){
                String fromCity = map.get("fromCity");
                fromDtAreaIds+=","+fromDtAreaId;
                fromDtAreaNames+="+"+fromCity;

            }

        }


        ordersGroupEntity.setToDtAreaIds(toDtAreaIds);
        ordersGroupEntity.setToDtAreaNames(toDtAreaNames);
        ordersGroupEntity.setFromDtAreaIds(fromDtAreaIds);
        ordersGroupEntity.setFromDtAreaNames(fromDtAreaNames);
        ordersGroupService.updateById(ordersGroupEntity);
        ordersDao.orderGroupOptionByIds(Constant.OrderStatus.ALREADY_CREATED_GROUP.getValue(),orderIds,orderGroupId);

    }

    @Override
    public Set<Map<String, String>> queryToDtAreaIdsByOrderIds(Collection<Integer> orderIds) {
        return ordersDao.queryToDtAreaIdsByOrderIds(orderIds);
    }

    @Override
    public List<TmsOrderVo> queryTmsImportData(Map<String, Object> params) {
        return ordersDao.queryTmsImportData(params);
    }

    @Override
    public int queryTmsImportDataTotal(Map<String, Object> params) {
        return ordersDao.queryTmsImportDataTotal(params);
    }


    private void setOrderAddress(OrdersEntity orders){
        AddressEntity fromAddress = orders.getFromAddress();
        if(fromAddress != null){

            orders.setFromAddressCode(fromAddress.getCode());
            orders.setFromAddressName(fromAddress.getName());
            orders.setFromAddressId(fromAddress.getId().toString());
            orders.setFromArea(fromAddress.getArea());
            orders.setFromCity(fromAddress.getCity());
            orders.setFromProvinceCode(fromAddress.getProvinceCode());
            orders.setFromCityCode(fromAddress.getCityCode());
            orders.setFromAreaCode(fromAddress.getAreaCode());
            orders.setFromDetailedAddress(fromAddress.getDetailedAddress());
            orders.setFromLinkMan(fromAddress.getLinkMan());
            orders.setFromLinkManEmail(fromAddress.getLinkManEmail());
            orders.setFromLinkManPhone(fromAddress.getLinkManPhone());
            orders.setFromProvince(fromAddress.getProvince());
            orders.setFromLinkManTelement(fromAddress.getLinkManTelement());
            orders.setFromOmsMnemonicCode(fromAddress.getDtAreaOmsMnemonicCode());
            orders.setFromDtAreaId(fromAddress.getDtAreaId());
        }
        AddressEntity toAddress = orders.getToAddress();
        if(toAddress != null){
            orders.setToAddressCode(toAddress.getCode());
            orders.setToAddressName(toAddress.getName());
            orders.setToAddressId(toAddress.getId().toString());
            orders.setToArea(toAddress.getArea());
            orders.setToCity(toAddress.getCity());
            orders.setToProvinceCode(toAddress.getProvinceCode());
            orders.setToCityCode(toAddress.getCityCode());
            orders.setToAreaCode(toAddress.getAreaCode());
            orders.setToDetailedAddress(toAddress.getDetailedAddress());
            orders.setToLinkMan(toAddress.getLinkMan());
            orders.setToLinkManEmail(toAddress.getLinkManEmail());
            orders.setToLinkManPhone(toAddress.getLinkManPhone());
            orders.setToProvince(toAddress.getProvince());
            orders.setToLinkManTelement(toAddress.getLinkManTelement());
            orders.setToDtAreaId(toAddress.getDtAreaId());
            orders.setToOmsMnemonicCode(toAddress.getDtAreaOmsMnemonicCode());
        }

    }


    private void saveOrderDetails(List<OrderDetailEntity> orderDetailEntities , Integer orderId){

        for (OrderDetailEntity o :
                orderDetailEntities) {
            if (o.getProductId() != null && o.getProductId().intValue() != 0) {
                o.setOrderId(orderId);
                detailService.insert(o);
            }
        }


    }

}
